package utils;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringEscapeUtils;
import org.apache.poi.poifs.filesystem.DirectoryEntry;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

import play.Play;


/**
 * @Description: TODO(将页面导出成word)
 * 
 */
public class HtmlToDoc {

	public static FileInputStream writeToWordFile(String html) throws Exception {
		html = enCodeHtml(html);
		ByteArrayInputStream bais = null;
		FileOutputStream fos = null;
		
		String dir = Play.applicationPath + File.separator+"public" + File.separator
				+ "uploadFile" + File.separator + "working";
		if (null == html) {
			throw new IllegalArgumentException("导出数据为空");
		}
		try {
			File fileDir = new File(dir);
			if (!fileDir.exists()) {
				fileDir.mkdirs();

			}
			File file = new File(dir + File.separator + "temp.doc");
			if (!file.exists()) {
				file.createNewFile();
				// throw new FileNotFoundException("创建文件失败");
			}
			byte b[] = html.getBytes("gbk");
			bais = new ByteArrayInputStream(b);
			POIFSFileSystem poifs = new POIFSFileSystem();
			DirectoryEntry directory = poifs.getRoot();
			directory.createDocument("WordDocument", bais);
			fos = new FileOutputStream(dir + File.separator + "temp.doc");
			poifs.writeFilesystem(fos);
			bais.close();
			fos.close();
			
			return new FileInputStream(dir + File.separator + "temp.doc");
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if (fos != null)
				fos.close();
			if (bais != null)
				bais.close();
		}
		return null;
	}

	/****
	 * wps 不能识别未经过编码的中文字符，所以把所有的中文字符都编码成html实体编码
	 * @param html
	 * @return
	 */
	public static String enCodeHtml(String html) {
		String regex = "[\u4e00-\u9fa5\u3002\uff1f\uff01\uff0c\u3001\uff1b\uff1a\u300c\u300d\u300e\u300f\u2018\u2019\u201c\u201d\uff08\uff09\u3014\u3015\u3010\u3011\u2014\u2026\u2013\uff0e\u300a\u300b\u3008\u3009]"; //汉字和标点
		Matcher matcher = Pattern.compile(regex).matcher(html);
		HashSet<String> set = new HashSet<String>();

		while (matcher.find()) {
			set.add(matcher.group());
		}
		for (String string : set) {
			html = html.replace(string, StringEscapeUtils.escapeHtml(string));
		}
		return html;
	}
}
